//
//  Utility.m
//  CardBag
//
//  Created by 恒信 on 11-4-1.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "Utility.h"
#import <commoncrypto/CommonDigest.h> 
#include <CommonCrypto/CommonCryptor.h>
#import <QuartzCore/QuartzCore.h>
#import <AVFoundation/AVFoundation.h>
#import "YY_Base64.h"
#include <sys/sysctl.h>
#include <mach/mach.h>
#include <sys/param.h>
#include <sys/mount.h>

#import "PublicMacros.h"


#define PI 3.1415926

#define Localizable_LF_Size_Bytes                                   @"%lld Bytes"
#define Localizable_LF_Size_K                                       @"%lld K"
#define Localizable_LF_Size_M                                       @"%lld.%lld M"
#define Localizable_LF_Size_G                                       @"%lld.%d G"
#define Localizable_LF_All_Size_M                                   @"%lld.%lld M"
#define Localizable_LF_All_Size_G                                   @"%lld.%lld G"

@implementation Utility

/******************************************************************************
 函数名称 : + (NSString *)stringForAllFileSize:(UInt64)fileSize
 函数描述 : 格式话返回文件大小
 输入参数 : (UInt64)fileSize
 输出参数 : N/A
 返回参数 : (NSString *)
 备注信息 :
 ******************************************************************************/
+ (NSString *)stringForAllFileSize:(UInt64)fileSize
{
    if (fileSize<1024) {//Bytes/Byte
        if (fileSize>1) {
            return [NSString stringWithFormat:Localizable_LF_Size_Bytes,
                    fileSize];
        }else {//==1 Byte
            return [NSString stringWithFormat:Localizable_LF_Size_Bytes,
                    fileSize];
        }
    }
    if ((1024*1024)>(fileSize)&&(fileSize)>1024) {//K
        return [NSString stringWithFormat:Localizable_LF_Size_K,
                fileSize/1024];
    }
    
    if ((1024*1024*1024)>fileSize&&fileSize>(1024*1024)) {//M
        return [NSString stringWithFormat:Localizable_LF_All_Size_M,
                fileSize/(1024*1024),
                fileSize%(1024*1024)/(1024*102)];
    }
    if (fileSize>(1024*1024*1024)) {//G
        return [NSString stringWithFormat:Localizable_LF_All_Size_G,
                fileSize/(1024*1024*1024),
                fileSize%(1024*1024*1024)/(1024*1024*102)];
    }
    return nil;
}

+ (CGFloat)textHeightWithFont:(NSString *)text withFont:(UIFont *)font sizeWidth:(float)width{
    if (width <= 0) {
        return 0;
    }
    
    CGSize size = CGSizeMake(width,2000.0);
    CGSize textsize = [text sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByWordWrapping];
    
    return textsize.height;
}

+ (CGFloat)textHeightWithStirng:(NSString *)inputString ShowFont:(UIFont *)font TitleFrame:(CGRect)frame
{
	CGSize size = CGSizeMake(frame.size.width,4000);
	CGSize labelsize = [inputString sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByWordWrapping];
	if(labelsize.height>frame.size.height)
	{
		return 	labelsize.height;
	}
	else 
	{
		return frame.size.height;
	}
}

+ (CGFloat)textWidthWithStirng:(NSString *)inputString ShowFont:(UIFont *)font sizeHeight:(CGFloat)height
{
	CGSize size = CGSizeMake(4000,height);
	CGSize labelsize = [inputString sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByWordWrapping];
	return labelsize.width;
}

+ (void)alert:(NSString *)msg
{
    UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:msg message:@"" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] autorelease];
    [alertView show];
}

+ (void)alert:(NSString *)title msg:(NSString *)msg
{
    UITextView *textView = [[UITextView alloc] init];
    textView.frame = CGRectMake(16, 65, 252, 210);
    textView.font = [UIFont systemFontOfSize:14.0];
    textView.text = msg;
    textView.editable = NO;
    
    textView.layer.cornerRadius = 6;  
    textView.layer.masksToBounds = YES; 
    UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:title message:@"\n\n\n\n\n\n\n\n\n\n" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] autorelease];
    [alertView addSubview:textView];
    [alertView show];
    [textView release];
}

+ (void)showError:(NSInteger)errNo errorMessage:(NSString *)errMsg
{
    if(errNo==0){
        UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:@"" message:errMsg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] autorelease];
        [alertView show];
    }
}

+ (NSString*) cleanPhoneNumber:(NSString*)phoneNumber
{
    NSString* number = [NSString stringWithString:phoneNumber];
    NSString* number1 = [[[[number stringByReplacingOccurrencesOfString:@" " withString:@""]
                          stringByReplacingOccurrencesOfString:@"-" withString:@""]
                          stringByReplacingOccurrencesOfString:@"(" withString:@""] 
                         stringByReplacingOccurrencesOfString:@")" withString:@""];
    
    return number1;    
}

+ (void) makeCall:(NSString *)phoneNumber
{ 
//    NSString* numberAfterClear = [Utility cleanPhoneNumber:phoneNumber]; 
//    //telprompt可以回调程序
//    NSURL *phoneNumberURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@", numberAfterClear]];
////    CardBagAppDelegate *appDelegate = (CardBagAppDelegate*)[[UIApplication sharedApplication] delegate];
//    HXAppDelegate *appDelegate = (HXAppDelegate*)[[UIApplication sharedApplication] delegate];
//    [[appDelegate defaultUIWebView] loadRequest:[NSURLRequest requestWithURL:phoneNumberURL]];
    
    NSString* numberAfterClear = [Utility cleanPhoneNumber:phoneNumber]; 
    //telprompt可以回调程序
    NSURL *phoneNumberURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@", numberAfterClear]];
    [[UIApplication sharedApplication] openURL:phoneNumberURL]; 
    
}

+ (void) makeCallPrompt:(NSString *)phoneNumber
{ 
    NSString* numberAfterClear = [Utility cleanPhoneNumber:phoneNumber]; 
    //telprompt可以回调程序
    NSURL *phoneNumberURL = [NSURL URLWithString:[NSString stringWithFormat:@"telprompt:%@", numberAfterClear]];
    [[UIApplication sharedApplication] openURL:phoneNumberURL];    
}

//十进制转十六进制
+ (int) getIntegerFromString:(NSString *)str
{
    int nValue = 0;
    for (int i = 0; i < [str length]; i++)
    {
        int nLetterValue = 0;
        
        if ([str characterAtIndex:i] >='0' && [str characterAtIndex:i] <='9') {
            nLetterValue += ([str characterAtIndex:i] - '0');
        }
        else{
            switch ([str characterAtIndex:i])
            {
                case 'a':case 'A':
                    nLetterValue = 10;break;
                case 'b':case 'B':
                    nLetterValue = 11;break;
                case 'c': case 'C':
                    nLetterValue = 12;break;
                case 'd':case 'D':
                    nLetterValue = 13;break;
                case 'e': case 'E':
                    nLetterValue = 14;break;
                case 'f': case 'F':
                    nLetterValue = 15;break;
                default:nLetterValue = '0';
            }
        }

        nValue = nValue * 16 + nLetterValue; //16进制
    }
    return nValue;
}

+ (NSString*)md5:(NSString*)str {
    if (str == nil || [str length] == 0) {
        return str;
    }
    const char*cStr =[str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result);
    return[NSString stringWithFormat:
           @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
           result[0], result[1], result[2], result[3],
           result[4], result[5], result[6], result[7],
           result[8], result[9], result[10], result[11],
           result[12], result[13], result[14], result[15]
           ];
}

#define CHUNK_SIZE 1024  
+(NSString *)file_md5:(NSString*) path {  
    NSFileHandle* handle = [NSFileHandle fileHandleForReadingAtPath:path];  
    if(handle == nil)  
        return nil;  
	
    CC_MD5_CTX md5_ctx;  
    CC_MD5_Init(&md5_ctx);  
	
    NSData* filedata;  
    do {  
        filedata = [handle readDataOfLength:CHUNK_SIZE];  
        CC_MD5_Update(&md5_ctx, [filedata bytes], [filedata length]);  
    }  
    while([filedata length]);  
	
    unsigned char result[CC_MD5_DIGEST_LENGTH];  
    CC_MD5_Final(result, &md5_ctx);  
	
    [handle closeFile];  
	
    return [NSString stringWithFormat:  
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",  
            result[0], result[1], result[2], result[3],  
            result[4], result[5], result[6], result[7],  
            result[8], result[9], result[10], result[11],  
            result[12], result[13], result[14], result[15]  
            ];  
} 

+(NSData *)DesEncryptWithKey:(NSData *)key data:(NSData *)data{
	//NSString *key = @"71543729";
	//byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
	
	//const void *vplainText;
	//size_t plainTextBufferSize;
	
	NSUInteger dataLength = [data length];
	//vplainText = (const void *) [str UTF8String];
	
	CCCryptorStatus cryptStatus;
	uint8_t *bufferPtr = NULL;
	size_t bufferPtrSize = 0;
	size_t movedBytes;
	
	bufferPtrSize = dataLength + kCCBlockSizeDES;
	bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
	memset((void *)bufferPtr, 0x0, bufferPtrSize);
	// memset((void *) iv, 0x0, (size_t) sizeof(iv));
	
	
	//NSString *initVec = @"init Vec";
	const void *vkey = (const void *) [key bytes];
	//const void *vinitVec = (const void *) [initVec UTF8String];
	
	cryptStatus = CCCrypt(kCCEncrypt,
                          kCCAlgorithmDES,
                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                          vkey, 
                          kCCKeySizeDES,
                          NULL,// vinitVec, //"init Vec", //iv,
                          [data bytes], 
                          dataLength,
                          (void *)bufferPtr,
                          bufferPtrSize,
                          &movedBytes);
	
	if (cryptStatus == kCCSuccess) {
		//return [NSData dataWithBytes:(const void *)bufferPtr length:movedBytes];
		NSData *resultData = [NSData dataWithBytes:(const void *)bufferPtr length:movedBytes];
		free(bufferPtr); //free the buffer;
		return resultData;
	}
	
	free(bufferPtr); //free the buffer;
	return nil;
}

+(NSData *)DesDecryptWithKey:(NSData *)key data:(NSData *)data{
	
	const void *keyPtr = (const void *) [key bytes];
	
	NSUInteger dataLength = [data length];
	
	//See the doc: For block ciphers, the output size will always be less than or 
	//equal to the input size plus the size of one block.
	//That's why we need to add the size of one block here
	size_t bufferSize = dataLength + kCCBlockSizeDES;
	void *buffer = malloc(bufferSize);
	
	size_t numBytesDecrypted = 0;
	CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
										  kCCAlgorithmDES, 
										  kCCOptionECBMode +kCCOptionPKCS7Padding,
										  keyPtr,
										  kCCKeySizeDES, // oorspronkelijk 256
										  NULL /* initialization vector (optional) */,
										  [data bytes],
										  dataLength, /* input */
										  buffer,
										  bufferSize, /* output */
										  &numBytesDecrypted);
	
	if (cryptStatus == kCCSuccess) {
		//the returned NSData takes ownership of the buffer and will free it on deallocation
		return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
	}
	
	free(buffer); //free the buffer;
	return nil;
}

//匹配Email地址的正则表达式：\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
+(BOOL)checkIsEmail:(NSString *)str
{
    return [str isMatchedByRegex:@"\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"];
}

//判断用户名是否合法
+(BOOL)stringIsLegalName:(NSString *)str
{
	return [str isMatchedByRegex:@"^[\\u4e00-\\u9fa5a-zA-Z_]{2,18}$"];
}

//判断密码是否合法
+(BOOL)checkIsLegalPassword:(NSString *)str
{
	return [str isMatchedByRegex:@"^[a-zA-Z0-9!@#$%^&*()-_=+:'<>,.?]{1,20}$"];
}

//判断字符串为空
+(BOOL)stringIsNull:(NSString *)str{
    if (str == nil || [str isEqualToString:@""]) {
        return YES;
    }
    else{
        return NO;
    }
}

//判断字符串长度（NSString类型字符串转换成类似ASCII编码的长度，如汉字2个字节，英文以及符号1个字节）
+ (int)convertToInt:(NSString*)strtemp
{
    int strlength = 0;
    char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding];
    for (int i=0 ; i<[strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {
        if (*p) {
            p++;
            strlength++;
        }
        else {
            p++;
        }
        
    }
    return strlength;
} 

+(NSString *)reverseString:(NSString *)str{

	int len = [str length];	 
    NSMutableString *reversedStr = [[NSMutableString alloc] initWithCapacity:len];
	
	while (len > 0)
	{
		[reversedStr appendString:[NSString stringWithFormat:@"%C", [str characterAtIndex:--len]]];   
	}
	return [reversedStr autorelease];

}

+ (NSString*)URLencode:(NSString *)originalString
        stringEncoding:(NSStringEncoding)stringEncoding {
 
    NSString* escapedUrlString= (NSString*) CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)originalString, NULL,(CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8);
    return [escapedUrlString autorelease];
//
//    escapedUrlString = [escapedUrlString stringByAddingPercentEscapesUsingEncoding:kCFStringEncodingUTF8];
//    return [escapedUrlString autorelease];
    
    
    //!  @  $  &  (  )  =  +  ~  `  ;  '  :  ,  /  ?
    //%21%40%24%26%28%29%3D%2B%7E%60%3B%27%3A%2C%2F%3F
    NSArray *escapeChars = [NSArray arrayWithObjects:@";" , @"/" , @"?" , @":" ,
                            @"@" , @"&" , @"=" , @"+" ,    @"$" , @"," ,
                            @"!", @"'", @"(", @")", @"*", nil];
    
    NSArray *replaceChars = [NSArray arrayWithObjects:@"%3B" , @"%2F", @"%3F" , @"%3A" ,
                             @"%40" , @"%26" , @"%3D" , @"%2B" , @"%24" , @"%2C" ,
                             @"%21", @"%27", @"%28", @"%29", @"%2A", nil];
    
    int len = [escapeChars count];
    
    NSMutableString *temp = [[originalString
                              stringByAddingPercentEscapesUsingEncoding:stringEncoding]
                             mutableCopy];
    
    int i;
    for (i = 0; i < len; i++) {
        
        [temp replaceOccurrencesOfString:[escapeChars objectAtIndex:i]
                              withString:[replaceChars objectAtIndex:i]
                                 options:NSLiteralSearch
                                   range:NSMakeRange(0, [temp length])];
    }
    
    NSString *outStr = [NSString stringWithString: temp];
	
	[temp release];
    
    return outStr;
}

+ (NSString *)stringFromDate:(NSDate *)date  forDateFormatterStyle:(DateFormatterStyle)dateFormatterStyle
{
	NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
	[formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterNoStyle];
    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CCT"]];
    
    if (dateFormatterStyle == DateFormatterDateAndTime) {
		[formatter setDateFormat:kDEFAULT_DATE_TIME_FORMAT];
	}
	else if (dateFormatterStyle == DateFormatterDate){
		[formatter setDateFormat:kDEFAULT_DATE_FORMAT];		
	}
	else if (dateFormatterStyle == DateFormatterTime){
		[formatter setDateFormat:kDEFAULT_TIME_FORMAT];
	}
    else if (dateFormatterStyle == DateFormatterDateAndTime2){
		[formatter setDateFormat:kDEFAULT_DATE_TIME_FORMAT2];
	}
	else {
		[formatter setDateFormat:kDEFAULT_DATE_FORMAT];		
	}

	return [formatter stringFromDate:date];
}

+ (NSNumber *)stringToNumber:(NSString *)string
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    NSNumber *number = [numberFormatter numberFromString:string];
    [numberFormatter release];
    return number;
}

+ (NSString *)numberToString:(NSNumber *)number{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    NSString *string = [numberFormatter stringFromNumber:number];
    [numberFormatter release];
    return string;
}

+ (NSString *)numberToString:(NSNumber *)number fractionDigits:(NSInteger)fractionDigits{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setMaximumFractionDigits:fractionDigits];
    [numberFormatter setMinimumFractionDigits:fractionDigits];
    NSString *string = [numberFormatter stringFromNumber:number];
    [numberFormatter release];
    return string;
}

+(NSString *)changeFloat:(NSString *)stringFloat zeroLength:(NSInteger)len
{ 
    const char *floatChars = [stringFloat UTF8String];
    NSInteger length = [stringFloat length];
    NSInteger dotPos = 0;
    int i = 0;
    for(; i<length; i++)
    {
        if(floatChars[i] == '.'){
            dotPos = i;
            break;
        }
    }
    
    NSString *returnString;
    if (dotPos < length-len) {
        returnString = [stringFloat substringToIndex:dotPos+len+1];
    }
    else{
        if (dotPos==0) {
            returnString = [NSString stringWithFormat:@"%@.00",stringFloat];
        }
        else{
            NSInteger zoreCount = dotPos + len + 1 - length;
            NSMutableString *appString = [[NSMutableString alloc] initWithCapacity:zoreCount];
            for (int j=0; j<zoreCount; j++) {
                [appString appendString:@"0"];
            }
            returnString = [NSString stringWithFormat:@"%@%@",stringFloat,appString];
            [appString autorelease];
        }
    }
    return returnString; 
}

+ (NSString *)generateUUID
{
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
    return [(NSString *)string autorelease];
}


+ (NSString *)generateTimestamp{
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
	[formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterNoStyle];
	[formatter setDateFormat:@"yyyyMMddHHmmss"];
    NSDate *nowData = [NSDate date];
	return [formatter stringFromDate:nowData];
}

+ (NSDate *)NSStringDateToNSDate:(NSString *)string forDateFormatterStyle:(DateFormatterStyle)dateFormatterStyle{   
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];

    if (dateFormatterStyle == DateFormatterDateAndTime) {
		[formatter setDateFormat:kDEFAULT_DATE_TIME_FORMAT];
	}
	else if (dateFormatterStyle == DateFormatterDate){
		[formatter setDateFormat:kDEFAULT_DATE_FORMAT];		
	}
	else if (dateFormatterStyle == DateFormatterTime){
		[formatter setDateFormat:kDEFAULT_TIME_FORMAT];
	}
    else if (dateFormatterStyle == DateFormatterDateAndTime3){
		[formatter setDateFormat:kDEFAULT_DATE_TIME_FORMAT3];
	}
	else {
		[formatter setDateFormat:kDEFAULT_DATE_FORMAT];		
	}
    
    NSDate *date = [formatter dateFromString:string];
    [formatter release];
    return date;
}

+(NSString *)weekWithDate:(NSDate *)date
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps = [calendar components:(NSWeekCalendarUnit | NSWeekdayCalendarUnit | NSWeekdayOrdinalCalendarUnit)
                        fromDate:date];
//    NSInteger week = [comps week]; // 今年的第几周
    NSInteger weekday = [comps weekday]; // 星期几（注意，周日是“1”，周一是“2”。。。。）
    NSString *weekName;
    switch (weekday) {
        case 1:
            weekName = @"星期日";
            break;
            
        case 2:
            weekName = @"星期一";
            break;
            
        case 3:
            weekName = @"星期二";
            break;
            
        case 4:
            weekName = @"星期三";
            break;
            
        case 5:
            weekName = @"星期四";
            break;
            
        case 6:
            weekName = @"星期五";
            break;
            
        case 7:
            weekName = @"星期六";
            break;
            
        default:
            weekName = @"星期日";
            break;
    }
    
    return weekName;
}

//计算两个时间差的两个函数
+ (NSString *)intervalFromLastDate: (NSString *) dateString1  toTheDate:(NSString *) dateString2
{
    NSArray *timeArray1=[dateString1 componentsSeparatedByString:@"."];
    dateString1=[timeArray1 objectAtIndex:0];
    
    NSArray *timeArray2=[dateString2 componentsSeparatedByString:@"."];
    dateString2=[timeArray2 objectAtIndex:0];
    
    //NSLog(@"%@.....%@",dateString1,dateString2);
    NSDateFormatter *date=[[NSDateFormatter alloc] init];
    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *d1=[date dateFromString:dateString1];
    
    NSTimeInterval late1=[d1 timeIntervalSince1970]*1;
    
    NSDate *d2=[date dateFromString:dateString2];
    
    NSTimeInterval late2=[d2 timeIntervalSince1970]*1;
    
    NSTimeInterval cha=late2-late1;
    NSString *timeString=@"";
    NSString *house=@"";
    NSString *min=@"";
    NSString *sen=@"";
    
    sen = [NSString stringWithFormat:@"%d", (int)cha%60];
    //        min = [min substringToIndex:min.length-7];
    //    秒
    sen=[NSString stringWithFormat:@"%@", sen];
    
    min = [NSString stringWithFormat:@"%d", (int)cha/60%60];
    //        min = [min substringToIndex:min.length-7];
    //    分
    min=[NSString stringWithFormat:@"%@", min];
    
    //    小时
    house = [NSString stringWithFormat:@"%d", (int)cha/3600];
    //        house = [house substringToIndex:house.length-7];
    house=[NSString stringWithFormat:@"%@", house];
    
    timeString=[NSString stringWithFormat:@"%@:%@:%@",house,min,sen];
    [date release];
    
    return timeString;
}

+ (NSString *)getMD5FromUrl:(NSString *)url {

    if ([Utility stringIsNull:url]) {
        return @"";
    }
	NSArray *array1 = [url componentsSeparatedByString:@"/"];
	if ([array1 count] > 0) {
		NSArray *array2 = [[array1 lastObject] componentsSeparatedByString:@"."];
		
		if ([array2 count] > 0) {
			return [array2 objectAtIndex:0];
		}
	}
    else{
        NSArray *array2 = [url componentsSeparatedByString:@"."];
		
		if ([array2 count] > 0) {
			return [array2 objectAtIndex:0];
		}
    }
	
	return @"";
}

+ (NSString *) trimAllSpaceString:(NSString *)string {
	if (string == nil || [string isEqualToString: @""]) {
		return @"";
	}
    
    NSArray *arrayString = [string componentsSeparatedByString:@" "];
    if([arrayString count]>0){
        NSMutableString *mString = [[NSMutableString alloc] init];
        for (NSString *str in arrayString) {
            if (![string isEqualToString: @" "]) {
                [mString appendString:str];
            }
        }
        return [mString autorelease];
    }
    else{
        return @"";
    }
}

+ (NSString *) trimLeftSpaceString:(NSString *)string {
	if (string == nil || [string isEqualToString: @""]) {
		return @"";
	}
    
   
    if([string length]>0){
        NSString *subString0 = [string substringToIndex:0];
        if ([subString0 isEqualToString:@" "]) {
            NSString *subString1 = [string substringFromIndex:1];
            return [Utility trimLeftSpaceString:subString1];
        }
        else{
            return string;
        }
    }
    else{
        return @"";
    }
}

+ (NSString *) trimRightSpaceString:(NSString *)string {
	if (string == nil || [string isEqualToString: @""]) {
		return @"";
	}
    
    if([string length]>0){
        NSString *subString0 = [string substringFromIndex:[string length] - 2];
        if ([subString0 isEqualToString:@" "]) {
            NSString *subString1 = [string substringToIndex:[string length] - 2];
            return [Utility trimRightSpaceString:subString1];
        }
        else{
            return string;
        }
    }
    else{
        return @"";
    }
}

+ (NSString *) subString:(NSString *)string length:(NSInteger)len {
	if (string == nil || [string isEqualToString: @""]) {
		return @"";
	}
    
    if([string length] > len){
        return [string substringToIndex:len];
    }
    else{
        return string;
    }
}

+ (NSString *) subStringWithRange:(NSString *)string range:(NSRange)range {
	if (string == nil || [string isEqualToString: @""]) {
		return @"";
	}
    
    if (string.length < range.location) {
        return @"";
    }
    else if([string length] < range.location + range.length){
        return [string substringFromIndex:range.location];
    }
    else{
        return [string substringWithRange:range];
    }
}

+ (NSString *) convertToString:(id)data {
	if (data == nil || data == [NSNull null]) {
		return @"";
	}
	
	return [NSString stringWithFormat:@"%@", data];
}

+ (BOOL) convertToBool:(id)data {
	if (data == nil || data == [NSNull null]) {
		return NO;
	}
	
	return [data boolValue];
}

+ (NSNumber *) convertToNumber:(id)data {
	if (data == nil || data == [NSNull null]) {
		return 0;
	}
	
	@try {
		return (NSNumber*)data;
	}
	@catch (NSException * e) {
		return 0;
	}
	@finally {
		
	}
}

+ (NSNumber *) convertToNumber:(id)data defaultValue:(NSInteger)defaultValue {
	if (data == nil || data == [NSNull null]) {
		return [NSNumber numberWithInt:defaultValue];
	}
	
	@try {
		return (NSNumber*)data;
	}
	@catch (NSException * e) {
		return [NSNumber numberWithInt:defaultValue];
	}
	@finally {
		
	}
}

+ (NSDate *) convertToDate:(id)data {
    if (data==nil) {
        return nil;
    }
	@try {
		NSString *strOrgValue = [Utility convertToString:data];
		
		NSString *strValue = nil;
		NSInteger strLength = [strOrgValue length];
		
		if (strLength >= 8) {
			NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//			[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
            [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CCT"]];//CTS
			if (strLength >= 16) {
                strValue = strOrgValue;
				[formatter setDateFormat:kDEFAULT_DATE_TIME_FORMAT];
            }
			else if (strLength == 14) {
				strValue = strOrgValue;
				[formatter setDateFormat:@"yyyyMMddHHmmss"];
            }else if (strLength == 10) {
				strValue = strOrgValue;
				[formatter setDateFormat:@"yyyy-MM-dd"];
			} else {
				strValue = [strOrgValue substringToIndex:8];
				[formatter setDateFormat:@"yyyyMMdd"];
			}
			
			NSDate *date = [formatter dateFromString:strValue];
			[formatter release];
			return date;
		}
		else {
			return [NSDate date];
		}
	}
	@catch (NSException * e) {
		return [NSDate date];
	}
	@finally {
		
	}
}

+ (NSDate *) convertToDate:(id)data forDateFormatter:(NSString *)dateFormatter{
    if (data==nil) {
        return nil;
    }
	@try {
		NSString *strOrgValue = [Utility convertToString:data];
		NSString *strValue = nil;
		if (strOrgValue.length >= dateFormatter.length) {
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
            strValue = [Utility subString:strOrgValue length:dateFormatter.length];
            [formatter setDateFormat:dateFormatter];
            
			
			NSDate *date = [formatter dateFromString:strValue];
			[formatter release];
			return date;
		}
		else {
			return [NSDate date];
		}
	}
	@catch (NSException * e) {
		return [NSDate date];
	}
	@finally {
		
	}
}

+ (NSString *) convertImageToBase64:(NSData *)imageData{
    if (imageData==nil) {
        return @"";
    }
    NSString *base64Image = [YY_Base64 encode:imageData];
    return base64Image;
}

+ (UIImage *) grayImage:(UIImage *)source  
{  
    int width = source.size.width;  
    int height = source.size.height;  
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();  
    
    CGContextRef context = CGBitmapContextCreate (nil,  
                                                  width,  
                                                  height,  
                                                  8,      // bits per component  
                                                  0,  
                                                  colorSpace,  
                                                  kCGBitmapByteOrderDefault);
    
    CGColorSpaceRelease(colorSpace);  
    
    if (context == NULL) {  
        return nil;  
    }  
    
    CGContextDrawImage(context,  
                       CGRectMake(0, 0, width, height), source.CGImage);  
    CGImageRef image = CGBitmapContextCreateImage(context);
    UIImage *grayImage = [UIImage imageWithCGImage:image];
	CGImageRelease(image);
	CGContextRelease(context);  
    
    return grayImage;  
} 

+ (UIImage*)scaleToSize:(UIImage*)img size:(CGSize)size  
{  
    // 创建一个bitmap的context  
    // 并把它设置成为当前正在使用的context  
    UIGraphicsBeginImageContext(size);  
    // 绘制改变大小的图片  
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];  
    // 从当前context中创建一个改变大小后的图片  
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();  
    // 使当前的context出堆栈  
    UIGraphicsEndImageContext();  
    // 返回新的改变大小后的图片  
    return scaledImage;  
} 

+ (BOOL) removeSqliteFile {
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
	NSString *storePath = [documentDirectory stringByAppendingPathComponent:@"CardBag.sqlite"];
	NSError *error = nil;
	
	if ([fileManager fileExistsAtPath:storePath]) {
		if ([fileManager removeItemAtPath:storePath error:&error]){
			NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"CardBag" ofType:@"sqlite"];
			if (defaultStorePath) {
				return [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
			}
		}
	}
	
	return NO;
}

+ (double)getLantAndLongDist:(double)lon1 lat:(double)lat1 lon:(double)lon2 lat:(double)lat2
{
    double er = 6378137; // 6378700.0f;
    //ave. radius = 6371.315 (someone said more accurate is 6366.707)
    //equatorial radius = 6378.388
    //nautical mile = 1.15078
    double radlat1 = PI*lat1/180.0f;
    double radlat2 = PI*lat2/180.0f;
    //now long.
    double radlong1 = PI*lon1/180.0f;
    double radlong2 = PI*lon2/180.0f;
    if( radlat1 < 0 ) radlat1 = PI/2 + fabs(radlat1);// south
    if( radlat1 > 0 ) radlat1 = PI/2 - fabs(radlat1);// north
    if( radlong1 < 0 ) radlong1 = PI*2 - fabs(radlong1);//west
    if( radlat2 < 0 ) radlat2 = PI/2 + fabs(radlat2);// south
    if( radlat2 > 0 ) radlat2 = PI/2 - fabs(radlat2);// north
    if( radlong2 < 0 ) radlong2 = PI*2 - fabs(radlong2);// west
    //spherical coordinates x=r*cos(ag)sin(at), y=r*sin(ag)*sin(at), z=r*cos(at)
    //zero ag is up so reverse lat
    double x1 = er * cos(radlong1) * sin(radlat1);
    double y1 = er * sin(radlong1) * sin(radlat1);
    double z1 = er * cos(radlat1);
    double x2 = er * cos(radlong2) * sin(radlat2);
    double y2 = er * sin(radlong2) * sin(radlat2);
    double z2 = er * cos(radlat2);
    double d = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)+(z1-z2)*(z1-z2));
    //side, side, side, law of cosines and arccos
    double theta = acos((er*er+er*er-d*d)/(2*er*er));
    double dist  = theta*er;
    return dist;
}

+ (UIImage *)getImageFronSource:(NSString *)imgName Type:(NSString *)imgType
{
    NSString *imgString = [[NSBundle mainBundle] pathForResource:imgName ofType:imgType];
    return [UIImage imageWithContentsOfFile:imgString];
}


+ (BOOL)validateMobile:(NSString *)mobileNum
{
#if 1
    NSString * MOBILE = @"^1\\d{10}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    return [regextestmobile evaluateWithObject:mobileNum];
#else
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
#endif // #if 1
}

+ (NSString*)getMobileOriginalModel
{
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = malloc(size);
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
    free(machine);
    
    return platform;
}

+ (NSString*)getMobileModel
{
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = malloc(size);
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
    free(machine);
    if ([platform isEqualToString:@"iPhone1,1"])    return @"iPhone 2G";
    if ([platform isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([platform isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([platform isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,2"])    return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,3"])    return @"iPhone 4 (CDMA)";
    if ([platform isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([platform isEqualToString:@"iPhone5,1"])    return @"iPhone 5";
    if ([platform isEqualToString:@"iPhone5,2"])    return @"iPhone 5 (GSM+CDMA)";
    
    if ([platform isEqualToString:@"iPod1,1"])      return @"iPod Touch (1 Gen)";
    if ([platform isEqualToString:@"iPod2,1"])      return @"iPod Touch (2 Gen)";
    if ([platform isEqualToString:@"iPod3,1"])      return @"iPod Touch (3 Gen)";
    if ([platform isEqualToString:@"iPod4,1"])      return @"iPod Touch (4 Gen)";
    if ([platform isEqualToString:@"iPod5,1"])      return @"iPod Touch (5 Gen)";
    
    if ([platform isEqualToString:@"iPad1,1"])      return @"iPad";
    if ([platform isEqualToString:@"iPad1,2"])      return @"iPad 3G";
    if ([platform isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
    if ([platform isEqualToString:@"iPad2,2"])      return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
    if ([platform isEqualToString:@"iPad2,4"])      return @"iPad 2";
    if ([platform isEqualToString:@"iPad2,5"])      return @"iPad Mini (WiFi)";
    if ([platform isEqualToString:@"iPad2,6"])      return @"iPad Mini";
    if ([platform isEqualToString:@"iPad2,7"])      return @"iPad Mini (GSM+CDMA)";
    if ([platform isEqualToString:@"iPad3,1"])      return @"iPad 3 (WiFi)";
    if ([platform isEqualToString:@"iPad3,2"])      return @"iPad 3 (GSM+CDMA)";
    if ([platform isEqualToString:@"iPad3,3"])      return @"iPad 3";
    if ([platform isEqualToString:@"iPad3,4"])      return @"iPad 4 (WiFi)";
    if ([platform isEqualToString:@"iPad3,5"])      return @"iPad 4";
    if ([platform isEqualToString:@"iPad3,6"])      return @"iPad 4 (GSM+CDMA)";
    
    if ([platform isEqualToString:@"i386"])         return @"iPhone 5";//@"Simulator";
    if ([platform isEqualToString:@"x86_64"])       return @"iPhone 5";//@"Simulator";
    return platform;
}

// 获取IOS版本信息
+ (NSString*)getIOSVersion
{
    return [NSString stringWithFormat:@"%@ %@", [[UIDevice currentDevice] systemName], [[UIDevice currentDevice] systemVersion]];
}

// 获取手机容量
+ (float)getMobileStroageSize
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    struct statfs tStats;
    statfs([[paths lastObject] cString], &tStats);
    float totalSpace = (float)(tStats.f_blocks * tStats.f_bsize);
    
    return totalSpace / 1024 / 1024 / 1024;
}

// 获取手机屏幕尺寸
+ (NSString*)getMobileScreenSize
{
    if ([[self getMobileModel] stringByMatching:@"iPhone 5"]
        || [[self getMobileModel] stringByMatching:@"iPod Touch (5"])
    {
        return @"4.0英寸";
    }
    else
    {
        return @"3.5英寸";
    }
}

// 获取手机屏幕分辨率
+ (NSString*)getMobileScreenPixelString
{
    return [NSString stringWithFormat:@"%dx%d", (int)[[UIScreen mainScreen] currentMode].size.width, (int)[[UIScreen mainScreen] currentMode].size.height];
}

+ (BOOL)validateEmail:(NSString *)candidate
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:candidate];
}


#pragma -mark ------------------------通用小方法--------------
+ (BOOL)findSubstring:(NSString *)substr inString:(NSString *)dststr
{
    if (dststr == nil || substr == nil) {
        return FALSE;
    }
    
    NSRange range = [dststr rangeOfString:substr];
    
    if (range.length >0)//包含
    {
        return TRUE;
    }
    else//不包含
    {
        return FALSE;
    }
}

//将某一字符从开始位置截取到指定字符处
+ (NSString *)truncateNSString:(NSString *)srcStr To:(NSString *)toStr
{
    if (srcStr == nil) {
        return nil;
    }
    NSRange range = [srcStr rangeOfString:toStr];
    NSString *str = [srcStr substringToIndex:range.location];
    return str;
}

//去除用户Id字符串中的@wx.com  和 @group.wx.com
+ (NSString *)getBareContactId:(NSString *)contactId
{
    if (contactId == nil ||[contactId isEqualToString:@""]) {
        return nil;
    }
    NSString *retval = contactId;
    if ([self findSubstring:kXMPPmyDomain inString:contactId]) {
        retval = [self truncateNSString:contactId To:kXMPPmyDomain];
    }
    if ([self findSubstring:kXMPPAndGroupDomain inString:retval]) {
        retval = [self truncateNSString:contactId To:kXMPPAndGroupDomain];
    }
    
    return retval;
}

#pragma mark-------------------------通用处理方法-----------------------------
+ (NSString *)convertToJid:(NSString *)jidName
{
    NSString *jidNameValid = nil;
    if (jidName != nil)
    {
        jidNameValid = [NSString stringWithString:jidName];
        NSRange range = [jidNameValid rangeOfString:kXMPPmyDomain];
        if (range.length >0)//包含
        {
        }
        else //不包含
        {
            jidNameValid = [NSString stringWithFormat:@"%@%@",jidName,kXMPPmyDomain];
        }
    }
    else
    {
        WXLog(@"convertToJid: jidName=NULL");
    }
    return jidNameValid;
}

+ (void)writeToFileWithString:(NSString *)aString withFileIsDelete:(BOOL)isDelete
{
    if (!aString) {
        NSLog(@"result is nil");
        return;
    }
    NSString  *documentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSFileManager *fileManager =[NSFileManager defaultManager];
    NSString *log = [documentsPath stringByAppendingPathComponent:@"netWorkConnectLog.txt"];
    if (log) {
        if (isDelete) {
            [fileManager removeItemAtPath:log error:nil];
            log = [documentsPath stringByAppendingPathComponent:@"netWorkConnectLog.txt"];
        }
    }
    if (![fileManager fileExistsAtPath:log]) {
        BOOL res = [fileManager createFileAtPath:log contents:nil attributes:nil];
        if (res) {
            NSLog(@"create success!");
        }
        else
        {
            NSLog(@"create error!");
            return;
        }
    }
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat : @"yyyy-MM-dd HH:mm:SS"];
    NSString *currentTime = [formatter stringFromDate:[NSDate date]];
    NSString *errorLog = [NSString stringWithFormat:@"%@errorLog:\n%@\n", currentTime, aString];
    
    NSFileHandle *outFile;
    outFile = [NSFileHandle fileHandleForWritingAtPath:log];
    [outFile seekToEndOfFile];
    [outFile writeData:[errorLog dataUsingEncoding:NSUTF8StringEncoding]];
}

+ (BOOL)muteSwitchEnabled {
    
#if TARGET_IPHONE_SIMULATOR
    // set to NO in simulator. Code causes crashes for some reason.
    return NO;
#endif
    
    // go back to Ambient to detect the switch
    AVAudioSession* sharedSession = [AVAudioSession sharedInstance];
    [sharedSession setCategory:AVAudioSessionCategoryAmbient error:nil];
    
    CFStringRef state;
    UInt32 propertySize = sizeof(CFStringRef);
    AudioSessionInitialize(NULL, NULL, NULL, NULL);
    AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state);
    
    BOOL muteSwitch = (CFStringGetLength(state) <= 0);
    NSLog(@"Mute switch: %d",muteSwitch);
    
    // code below here is just restoring my own audio state, YMMV
    BOOL _hasMicrophone = [sharedSession inputIsAvailable];
    NSError* setCategoryError = nil;
    
    if (_hasMicrophone) {
        
        [sharedSession setCategory: AVAudioSessionCategoryPlayAndRecord error: &setCategoryError];
        
        // By default PlayAndRecord plays out over the internal speaker.  We want the external speakers, thanks.
        UInt32 ASRoute = kAudioSessionOverrideAudioRoute_Speaker;
        AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,
                                 sizeof (ASRoute),
                                 &ASRoute
                                 );
    }
    else
        // Devices with no mike don't support PlayAndRecord - we don't get playback, so use just playback as we don't have a microphone anyway
        [sharedSession setCategory: AVAudioSessionCategoryPlayback error: &setCategoryError];
    
    if (setCategoryError)
        NSLog(@"Error setting audio category! %@", setCategoryError);
    
    return muteSwitch;
}

@end


@implementation UIColor(private)
//可以传入#FFFFFF类型的颜色值,必须以"#"开头
+ (UIColor *)colorwithString:(NSString *)colorValue colorAlpha:(float)alpha{
    
    UIColor *color = [UIColor clearColor];
    
    if ([[colorValue substringToIndex:1] isEqualToString:@"#"]) {
        
        if ([colorValue length]==7) {
            NSRange range = NSMakeRange(1,2);
            NSString *strRed = [colorValue substringWithRange:range];
            
            range.location = 3;
            NSString *strGreen = [colorValue substringWithRange:range];
            
            range.location = 5;
            NSString *strBlue = [colorValue substringWithRange:range];
            
            
            float r = [Utility getIntegerFromString:strRed];
            float g = [Utility getIntegerFromString:strGreen];
            float b = [Utility getIntegerFromString:strBlue];
            
            color = [UIColor colorWithRed:r/255 green:g/255 blue:b/255 alpha:alpha];
        }
    }
    else
    {
        NSAssert(0, @"don't # ");
    }
    return color;
}

@end

